package com.lihh.rocket5.normal;

import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.io.UnsupportedEncodingException;

/**
 * 以 异步的方式 发送消息
 *
 * @author lihh
 */
public class AsyncProducer {
  public static void main(String[] args) throws MQClientException, UnsupportedEncodingException, RemotingException, InterruptedException {
    // 拿到 producer 实例
    DefaultMQProducer producer = new DefaultMQProducer("group_test");
    // 设置 name server
    producer.setNamesrvAddr("127.0.0.1:9876");
    // 启动 producer实例
    producer.start();
    
    for (int i = 0; i < 10; i++) {
      final int index = i;
      Message message = new Message("order002", "TagA", ("hello async producer " + i).getBytes(RemotingHelper.DEFAULT_CHARSET));
      producer.send(message, new SendCallback() {
        @Override
        public void onSuccess(SendResult sendResult) {
          System.out.printf("%s%n", sendResult);
        }
        
        @Override
        public void onException(Throwable e) {
          System.out.printf("%-10d Exception %s %n", index, e);
          e.printStackTrace();
        }
      });
    }
    
    Thread.sleep(1000);
    producer.shutdown();
  }
}
